﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Abacus;
using Abacus.Database;

namespace Abacus.Presentation
{
    public partial class SettingsForm : Form
    {
        private FinanceDataSet.SettingsRow mInflationRateRow = null;
        private FinanceDataSet.SettingsRow mInterestOnSavingsRow = null;
        private FinanceDataSet.SettingsRow mInterestOnDeficitsRow = null;

        public SettingsForm()
        {
            InitializeComponent();
        }

        private void InterestRatesForm_Load(object sender, EventArgs e)
        {
            loadData();
            loadGeneralSettingsIntoGui();
        }

        private void loadData()
        {
            this.settingsTableAdapter.Fill(this.financeDataSet.Settings);
            this.assetTypesTableAdapter.Fill(this.financeDataSet.AssetTypes);
            this.loanTypesTableAdapter.Fill(this.financeDataSet.LoanTypes);
            this.expenseTypesTableAdapter.Fill(this.financeDataSet.ExpenseTypes);
        }

        private void loadGeneralSettingsIntoGui()
        {
            FinanceDataSet.SettingsRow[] results = null;

            // average inflation rate
            results = financeDataSet.Settings.Select("name = 'inflationRate'") as FinanceDataSet.SettingsRow[];
            if (results != null && results.Length > 0)
            {
                mInflationRateRow = results[0];
                inflationTextBox.Text = mInflationRateRow.floatValue.ToString();
            }

            // interest on saved surpluses
            results = financeDataSet.Settings.Select("name = 'interestOnSurplusSavingsAccount'") as FinanceDataSet.SettingsRow[];
            if (results != null && results.Length > 0)
            {
                mInterestOnSavingsRow = results[0];
                interestOnSavingsTextbox.Text = mInterestOnSavingsRow.floatValue.ToString();
            }

            // interest on loans for deficit coverage
            results = financeDataSet.Settings.Select("name = 'interestOnDeficitCoverageLoan'") as FinanceDataSet.SettingsRow[];
            if (results != null && results.Length > 0)
            {
                mInterestOnDeficitsRow = results[0];
                interestOnDeficitsTextbox.Text = mInterestOnDeficitsRow.floatValue.ToString();
            }
        }

        private void saveData()
        {
            this.settingsTableAdapter.Update(this.financeDataSet.Settings);
            this.assetTypesTableAdapter.Update(this.financeDataSet.AssetTypes);
            this.loanTypesTableAdapter.Update(this.financeDataSet.LoanTypes);
            this.expenseTypesTableAdapter.Update(this.financeDataSet.ExpenseTypes);
        }

        private void interestTextBox_Validating(object sender, CancelEventArgs e)
        {
            TextBox textbox = sender as TextBox;

            try
            {
                double percentageVal = double.Parse(textbox.Text);

                if (percentageVal < -100.0 || percentageVal > 100)
                    throw new FormatException();

                errorProvider.SetError(textbox, "");
            }
            catch(System.FormatException)
            {
                e.Cancel = true;
                errorProvider.SetError(textbox, GenResources.InvalidPercentageError);
            }
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            saveData();

            this.Close();
        }

        private void inflationTextBox_Validated(object sender, EventArgs e)
        {
            double inflationVal = double.Parse(inflationTextBox.Text);

            mInflationRateRow.floatValue = inflationVal;
        }

        // Displays an message box explaining why a cell valid is invalid.
        // If the user presses 'Cancel', changes to the cell are discarded. Otherwise,
        // focus is returned to the invalid cell so that any issues can be resolved.
        private void showInvalidCellError(string formatErrorMsg, DataGridViewCellValidatingEventArgs e, DataGridView source)
        {
            DialogResult result = MessageBox.Show(this, formatErrorMsg, GenResources.InvalidDataMessageBoxTitle, MessageBoxButtons.OKCancel);

            if (result == DialogResult.Cancel)
                source.CancelEdit();
            else
                e.Cancel = true;
        }

        private void loanTypesDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            String formatErrorMsg = null;

            try
            {
                switch (e.ColumnIndex)
                {
                    case 1: // percentage
                        formatErrorMsg = GenResources.InvalidDollarValueError;
                        double.Parse(e.FormattedValue as String, System.Globalization.NumberStyles.Float);
                        break;
                }
            }
            catch (FormatException)
            {
                showInvalidCellError(formatErrorMsg, e, loanTypesDataGridView);
            }
        }

        private void assetTypesDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            String formatErrorMsg = null;

            try
            {
                switch (e.ColumnIndex)
                {
                    case 1: // percentage
                        formatErrorMsg = GenResources.InvalidDollarValueError;
                        double.Parse(e.FormattedValue as String, System.Globalization.NumberStyles.Float);
                        break;
                }
            }
            catch (FormatException)
            {
                showInvalidCellError(formatErrorMsg, e, assetTypesDataGridView);
            }
        }

        private void interestOnDeficitsTextbox_Validated(object sender, EventArgs e)
        {
            double interestVal = double.Parse(interestOnDeficitsTextbox.Text);

            mInterestOnDeficitsRow.floatValue = interestVal;
        }

        private void interestOnSavingsTextbox_Validated(object sender, EventArgs e)
        {
            double interestVal = double.Parse(interestOnSavingsTextbox.Text);

            mInterestOnSavingsRow.floatValue = interestVal;
        }
    }
}
